<template>
    <div id="mindMap" @keydown="keydown" @keyup="keyup" @click="click">
        <div class="tools">

            <div class="flex-center">
                <div class="mindmap-handle" @click="createMindMap">
                    <img class="handle-img" src="../../assets/img/add-mindmap.png" alt="">
                    <span class="handle-text s-20">新建</span>
                </div>
                <div class="mindmap-handle" @click="saveMind">
                    <img class="handle-img" src="../../assets/img/save-mindmap.png" alt="">
                    <span class="handle-text s-20">保存</span>
                </div>
                <div class="mindmap-handle" @click="openMindMap">
                    <img class="handle-img" src="../../assets/img/select-mindmap.png" alt="">
                    <span class="handle-text s-20">打开</span>
                </div>
                <div class="mindmap-handle" @click="zoom('in')">
                    <span class="sub">
                        <i class="el-icon-zoom-in"></i>
                    </span>
                    <span class="handle-text s-20">放大</span>
                </div>
                <div class="mindmap-handle" @click="zoom('out')">
                    <span class="sub">
                        <i class="el-icon-zoom-out"></i>
                    </span>
                    <span class="handle-text s-20">缩小</span>
                </div>
                <div class="mindmap-handle" @click="exportImg">
                    <img class="handle-img" src="../../assets/img/export_mindMap.png" alt="">
                    <span class="handle-text s-20">导出</span>
                </div>
                <!-- <el-tooltip class="item" effect="light" placement="right" style="margin-left: 20px;">
                    <div slot="content" class="tooltip " style="list-style:disc;padding:0 10px;">
                        <li style="list-style: none;">导出注意事项:</li>
                        <li style="margin-top: 5px;">请确认思维导图节点已全部显示</li>
                        <li style="margin-top: 5px;">思维导图超出屏幕右侧将被覆盖</li>
                        <li style="margin-top: 5px;">将思维导图适当左移可使导出图片更居中</li>
                        <li style="margin-top: 5px;">放大字体可使导出图片更加清晰</li>
                    </div>
                    <i class="el-icon-question" />
                </el-tooltip> -->
            </div>
            <!-- <div class="flex-center" style="margin-bottom:15px">
                <div class="block flex-center">
                    <span class="demonstration">设置节点横向间隔：</span>
                    <el-slider style="width:200px" v-model="xSpacing" :show-tooltip="false"></el-slider>
                </div>
                <div class="block flex-center" style="margin:0 20px">
                    <span class="demonstration">设置节点纵向间隔 ：</span>
                    <el-slider style="width:200px" v-model="ySpacing" :show-tooltip="false"></el-slider>
                </div>
                <div class="block flex-center">
                    <span class="demonstration">设置连线的宽度：</span>
                    <el-slider style="width:200px" v-model="strokeWidth" :max="10" :show-tooltip="false"></el-slider>
                </div>
            </div> -->
        </div>
        <div class="mouse" @touchstart="mousedown" @mousedown="mousedown" ref="container">
            <div ref="mind" id="mindWraper" class="mind-container" style="height:100%;">
                <mindmap @dblclick.native="arouseKeyBord" v-model="data" :xSpacing="xSpacing" :ySpacing="ySpacing" :strokeWidth="2" :download="false" style="height:500%;transform:translate(0,-40%)"  :showUndo="false" :fitView="false" :gps="false">
                </mindmap>
            </div>
            <el-dialog title="选择文件" :visible.sync="dialogVisible" width="50%" v-if="dialogVisible">
                <div>
                    <div>
                        <el-select v-model="searchParam" placeholder="选择年级" clearable>
                            <el-option v-for="(item,index) in gradeList" :key="index" :label="item" :value="item">
                            </el-option>
                        </el-select>
                        <el-button style="margin-left: 10px;" type="primary" @click="search('gradeName')">搜索</el-button>
                        <el-button style="margin-left: 10px;" type="primary" @click="syncFile()">同步文件</el-button>
                    </div>
                    <el-table ref="singleTable" :data="paginationData" highlight-current-row @current-change="handleCurrentChange" style="width: 100%">
                        <el-table-column type="selection" label="序号" width="100">
                        </el-table-column>
                        <el-table-column property="fileName" label="文件名">
                        </el-table-column>
                        <el-table-column property="gradeName" label="年级">
                        </el-table-column>
                        <el-table-column property="creatDate" label="创建时间">
                        </el-table-column>
                        <el-table-column property="fileType" label="文件类型">
                        </el-table-column>
                        <el-table-column label="操作" width="50">
                            <template slot-scope="scope">
                                <el-button type="text" style="color:#F56C6C" :disabled="!scope.row.originPath" @click="deleteFile(scope.$index,scope.row.originPath)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div>
                    <el-pagination :page-size="pageSize" @current-change="paginationChange" :hide-on-single-page="true" :total="tableList.length" layout="total,prev, pager, next">
                    </el-pagination>
                </div>
                <div slot="footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="changeMindMap">确 定</el-button>
                </div>
            </el-dialog>
        </div>
        <el-dialog title="提示" :visible.sync="chooseGrade" width="500px">
            <div>
                <div style="margin-bottom:15px">
                    <span style="width:80px;display: inline-block;">
                        文件名：
                    </span>
                    <el-input style="width:250px" v-model="customFileName" placeholder="请填写文件名"></el-input>
                </div>
                <div>
                    <span style="width:80px;display: inline-block;">
                        选择年级：
                    </span>
                    <el-select v-model="gradeName" placeholder="请选择年级">
                        <el-option v-for="(item,index) in gradeList" :key="item+'_'+index" :label="item" :value="item">
                        </el-option>
                    </el-select>
                </div>
            </div>
            <div slot="footer">
                <el-button type="primary" :disabled="!!!gradeName" @click="confirm">确 定</el-button>
                <el-button @click="chooseGrade = false">取 消</el-button>
            </div>
        </el-dialog>
       
    </div>
</template>

<script>
import {queryUserMindMaps , createUserMindMap , delUserMindMap} from '../../api/mindMap.js'
import mixin from '../../mixin/mixin'
import mindmap from '@hellowuxin/mindmap'
import html2canvas from 'html2canvas';
import moment from 'moment'
const fs = require('fs')
const path = require('path')
let isKeyDown = false //标志键盘按下
const {dialog} = require("electron").remote
const copyData = [{
    "name": "中心主题",
    children: [
        {

            left: false,
            name: "分支主题一"
        },
        {

            left: false,
            name: "分支主题二"
        },
        {

            left: false,
            name: "分支主题三"
        },
        {

            left: false,
            name: "分支主题四"
        }
    ]
}]
let cacheTableData = []//缓存表格初始数据
let isChange = true //标志文件列表是否有变化
let lockArouse = false // 标志软键盘是否弹起
export default {
    mixins: [mixin],
    components: { mindmap },
    data () {
        return {
            data: [{
                "name": "中心主题",
                children: [
                    {

                        left: false,
                        name: "分支主题一"
                    },
                    {

                        left: false,
                        name: "分支主题二"
                    },
                    {

                        left: false,
                        name: "分支主题三"
                    },
                    {

                        left: false,
                        name: "分支主题四"
                    }
                ]
            }],
            lessonId: '',
            scale: 1.2,
            dialogVisible: false,
            exportPreView:false,
            tableList: [],
            xSpacing: 60,
            ySpacing: 20,
            strokeWidth: 5,
            currentRow: null,
            currentPage: 1,
            pageSize: 8,
            gradeList: ['一年级', '二年级', '三年级', '四年级', '五年级', '六年级','全部'],
            gradeName: '',
            chooseGrade: false,
            openExportImg:false,
            exportImgUrl:'',
            searchParam: '',
            customFileName: '',
            event:'',
            active: false,
        }
    },
    created () {
        if (this.bsr && this.bsr.resourceJson) {
            console.log('bsr.resourceJson=>>>', this.bsr.resourceJson)
            this.data = JSON.parse(this.bsr.resourceJson)
        }
    },
    computed: {
        paginationData () {
            let arr = []
            const start = (this.currentPage - 1) * this.pageSize
            //存在无用的循环暂不优化
            for (let index = 0; index < this.pageSize; index++) {
                this.tableList[start + index] && arr.push(this.tableList[start + index])
            }
            return arr
        }
    },
    mounted () {
        this.$nextTick(() => {
            this._dom = document.getElementById('content');
            let transform = ''
            let interval = setInterval(() => {
                try {
                    transform = this._dom.attributes.transform
                    if (transform) {
                        transform = transform.value.toString()
                        transform = transform.replace(/scale.*/, `scale(${this.scale})`).replace(/(\,[0-9]*)/, 'px$1px')
                        this._dom.style.transform = transform
                        clearInterval(interval)
                    }
                } catch (error) {
                    clearInterval(interval)
                }
            }, 100)
        })
    },
    methods: {
        exportImg(){
            this.$dialog({
                confirm: '是',
                cancel: '否',
                message: '温馨提示:\n1、请确认思维导图节点已全部显示\n2、请确认思维导图未超出屏幕右侧\n3、点击放大可以使导出文件更清晰',
                close: true,
                type: "warn",
            }).then(_ => {
                let mindWraper = document.getElementById('mindmap')
                let content = document.getElementById('content');
                console.log(mindWraper);
                console.log(content);
                html2canvas(mindWraper,{allowTaint:true,useCORS:true}).then(canvas => {
                    mindWraper.appendChild(canvas)
                    // this.exportPreView = true
                    // this.exportImgUrl = canvas.toDataURL()
                    let base64 = canvas.toDataURL().replace(/^data:image\/\w+;base64,/, "");
                    let dataBuffer = new Buffer(base64, 'base64');
                    let dia = dialog.showSaveDialog({
                        title: "保存",
                        filters: [{name: "IMG", extensions: ['png', 'jpg']}],
                        defaultPath: this.data[0].name,
                    })
                    const fs = require('fs')
                    let _this = this
                    fs.writeFile(dia, dataBuffer, function (err) {
                        if (err) {
                           console.log(err)
                        } else {
                            _this.$message.success('保存成功')
                            setTimeout(() => {
                                let canvas = document.getElementsByTagName('canvas')
                                console.log(canvas);
                                for (let i = 0; i < canvas.length; i++) {
                                    canvas[i].style.display = 'none'
                                }
                            }, 0);
                        }
                        setTimeout(() => {
                            let canvas = document.getElementsByTagName('canvas')
                            console.log(canvas);
                            for (let i = 0; i < canvas.length; i++) {
                                canvas[i].style.display = 'none'
                            }
                        }, 0);
                    })
                    
                });
            }).catch(_ => {
            }) 
            
        },
        click () {
            if (this._keyDown) {
                console.log('move')
            }
        },
        syncFile(){
            console.log(this.tableList);
            queryUserMindMaps({
                appkey:'NOVO_EDU_BEAUTY_SCIENCE_PC'
            }).then(res=>{
                console.log(res);
                if (res.returnValue.length !== 0) {
                    this.savesyncFile(res.returnValue)
                }else{
                    this.$message.warning('暂无可同步文件')
                }
            })
        },
        mousedown (e) {
            console.log(e)
            this.event = e
            const { type } = e
            let clientX = 0
            let clientY = 0
            if (type === 'touchstart') {
                clientX = e.changedTouches[0].clientX
                clientY = e.changedTouches[0].clientY
            } else {
                clientX = e.clientX
                clientY = e.clientY
            }
            this._X = clientX
            this._Y = clientY
            this._marginLeft = parseInt(this.$refs.mind.style.marginLeft)
            this._marginTop = parseInt(this.$refs.mind.style.marginTop)
            this.$refs.container.addEventListener('touchmove', this.mousemove)
            this.$refs.container.addEventListener('mousemove', this.mousemove)
            document.documentElement.addEventListener('touchend', this.mouseup)
            document.documentElement.addEventListener('mouseup', this.mouseup)
        },
        mousemove (e) {
            const { type } = e
            console.log(type)
            let clientX = 0
            let clientY = 0
            if (type === 'touchmove') {
                clientX = e.changedTouches[0].clientX
                clientY = e.changedTouches[0].clientY
            } else {
                clientX = e.clientX
                clientY = e.clientY
            }
            this.$refs.mind.style.marginLeft = clientX - this._X + (this._marginLeft || 0) + 'px'
            this.$refs.mind.style.marginTop = clientY - this._Y + (this._marginTop || 0) + 'px'
            console.log(this.$refs.mind.style.marginLeft)
        },
        mouseup () {
            this.$refs.container.removeEventListener('mousemove', this.mousemove)
            this.$refs.container.removeEventListener('touchmove', this.mousemove)
            document.documentElement.removeEventListener('mouseup', this.mouseup)
            document.documentElement.removeEventListener('touchend', this.mouseup)
        },
        keydown (e) {
            if (isKeyDown) return
            if (e.keyCode === 32) {
                isKeyDown = true
            }
        },
        keyup () {
            isKeyDown = false
        },
        createMindMap () {
            this.$dialog({
                confirm: '保存',
                cancel: '取消',
                message: '是否保存改动？',
                close: false,
                type: "warn"
            }).then(_ => {
                this._init = true
                this.saveMind()
            }).catch(_ => {
                this.initData()
            })

        },
        initData () {
            this.data = [{
                "name": "中心主题",
                children: [
                    {

                        left: false,
                        name: "分支主题一"
                    },
                    {

                        left: false,
                        name: "分支主题二"
                    },
                    {

                        left: false,
                        name: "分支主题三"
                    },
                    {

                        left: false,
                        name: "分支主题四"
                    }
                ]
            }]
            this.customFileName = ''
            this.currentRow = null
        },
        saveMind () {
            this.chooseGrade = true
        },
        confirm () {
            this.writeMindFile()
            this.chooseGrade = false
        },
        savesyncFile(syncFile){
            syncFile.forEach(item=>{
                var filePath = ''
                filePath = path.join(window.$DATADIR, 'resc', 'user', 'mindMap', item.fileName + '_b_s_c_' + item.id + '%%%' + item.gradeName + '.json')
                if (fs.existsSync(filePath)) {
                    console.log('本地已经有了');
                    fs.unlinkSync(filePath)
                }
                let data = new Uint8Array(Buffer.from(item.resJson))
                fs.writeFile(filePath, data, (err) => {
                    if (err) {
                        console.log(err)
                        this.$message.error('同步失败')
                        return
                    }
                    this.dialogVisible = false
                    isChange = true
                    this.$message.success('同步成功')
                })
            })
        },
        writeMindFile () {
            if (!this.gradeName) return
            isChange = true
            let data = new Uint8Array(Buffer.from(JSON.stringify(this.data)))
            let filePath = ''
            if (this.currentRow && this.currentRow.originPath) {
                const oldPath = path.join(window.$DATADIR, 'resc', 'user', 'mindMap', this.currentRow.originPath)
                if (fs.existsSync(oldPath)) {
                    fs.unlinkSync(oldPath)
                }
            }
            filePath = path.join(window.$DATADIR, 'resc', 'user', 'mindMap', (this.customFileName ? this.customFileName : this.data[0].name) + '_b_s_c_' + Date.now() + '%%%' + this.gradeName + '.json')
            if (fs.existsSync(filePath)) {
                fs.unlinkSync(filePath)
            }
            fs.writeFile(filePath, data, (err) => {
                if (err) {
                    console.log(err)
                    this.$message.error('保存失败')
                    return
                }
                this.$message.success('保存成功')
                var flag = filePath.indexOf('_b_s_c_')+7
                var Id = filePath.substring(flag ,flag+13 )
                createUserMindMap({ //上传云端
                    gradeName:this.gradeName,
                    resJson:JSON.stringify(this.data),
                    fileName:this.customFileName,
                    id:Id,
                })
                if (this._init) {
                    this.currentRow = null
                    this.customFileName = ''
                    // this.initData()
                    this._init = false
                }
            })
        },
        async openMindMap () {
            if (!isChange) {
                this.dialogVisible = true
                return
            }
            let dirPath = path.join(window.$DATADIR, 'resc', 'user', 'mindMap')
            let systemDirPath = path.join(window.$DATADIR, 'resc', 'MindMap')
            let fileList = await fs.promises.readdir(dirPath)
            let systemFile = await fs.promises.readdir(systemDirPath)
            let data = []
            if (Array.isArray(fileList)) {
                fileList.forEach(item => {
                    console.log(item)
                    if (!item.includes('.json')) return
                    let message = item.replace('.json', '').split('_b_s_c_')
                    message = [message[0], ...message[1].split('%%%')]
                    if (message[0] && !isNaN(Date.parse(new Date(message[1])))) return
                    let obj = { fileName: '', creatDate: '', originPath: '', fileType: '', gradeName: '' }
                    obj.fileName = message[0]
                    obj.creatDate = moment(parseInt(message[1])).format('YYYY-MM-DD HH:mm:ss')
                    obj.originPath = item
                    obj.gradeName = message[2]
                    obj.fileType = '用户资源'
                    data.push(obj)
                })
            }
            // if (Array.isArray(systemFile)) {
            //     systemFile.forEach(item => {
            //         console.log(item)
            //         if (!item.includes('.json')) return
            //         const suffix = item.replace('.json', '').split('_b_s_c_')[1]
            //         let message = suffix && suffix.split('_')
            //         if (message[0] && !isNaN(Date.parse(new Date(message[1])))) return
            //         let obj = { fileName: '', creatDate: '', originPath: '', fileType: '', gradeName: '' }
            //         obj.fileName = message[0]
            //         obj.creatDate = moment(parseInt(message[1])).format('YYYY-MM-DD hh:mm:ss')
            //         obj.systemPath = item
            //         obj.gradeName = '内置资源'
            //         obj.fileType = '内置资源'
            //         data.push(obj)
            //     })
            // }
            this.tableList = data.sort((itemA, itemB) => new Date(itemB.creatDate).getTime() - new Date(itemA.creatDate).getTime())
            console.log(this.tableList);
            cacheTableData = this.tableList
            this.dialogVisible = true
            isChange = false
        },
        changeMindMap () {
            if (this._filePath) {
                if (fs.existsSync(this._filePath)) {
                    const fileRes = fs.readFileSync(this._filePath)
                    if (fileRes) {
                        this.data = JSON.parse(fileRes.toString())
                        console.log(this.data);
                    }
                }
            }
            this._filePath = null
            this.dialogVisible = false
        },
        zoom (type) {
            let min = 0.5 //定义最小缩放
            let max = 3 //定义最大缩放
            let scale = this.scale + (type === 'in' ? 0.2 : -0.2)
            if (this.scale < min && type === 'out') return
            if (this.scale > max && type === 'in') return
            this.scale = scale
            this._dom.style.transform = this._dom.style.transform.replace(/scale.*/, `scale(${this.scale})`)
        },
        setCurrent (row) {
            this.$refs.singleTable.setCurrentRow(row);
        },
        handleCurrentChange (val) {
            this.currentRow = val
            this.gradeName = val.gradeName === '内置资源' ? '' : val.gradeName
            if (this.currentRow.originPath) {
                this._filePath = path.join(window.$DATADIR, 'resc', 'user', 'mindMap', this.currentRow.originPath)
            } else {
                this._filePath = path.join(window.$DATADIR, 'resc', 'MindMap', this.currentRow.systemPath)
            }
        },
        deleteFile (index, filePath) {
            this.$dialog({
                confirm: '是',
                cancel: '否',
                message: '您正在删除本地资源，是否保留云端数据？',
                close: true,
                type: "warn",
            }).then(_ => {
                const path = require('path')
                const fullPath = path.join(window.$DATADIR, 'resc', 'user', 'mindMap', filePath)
                console.log(fullPath)
                if (!fs.existsSync(fullPath)) return
                fs.unlinkSync(fullPath)
                this.tableList.splice(index, 1)
                isChange = true
                this.$message.success('删除成功')
            }).catch(_ => {
                var flag = filePath.indexOf('_b_s_c_')+7
                var Id = filePath.substring(flag ,flag+13 )
                delUserMindMap({
                    id:Id,
                })
                const path = require('path')
                const fullPath = path.join(window.$DATADIR, 'resc', 'user', 'mindMap', filePath)
                console.log(fullPath)
                if (!fs.existsSync(fullPath)) return
                fs.unlinkSync(fullPath)
                this.tableList.splice(index, 1)
                isChange = true
                this.$message.success('删除成功')
            }) 
        },
        paginationChange (val) {
            this.currentPage = val
        },
        search (type) {
            console.log(this.searchParam);
            this.tableList = JSON.parse(JSON.stringify(cacheTableData))
            if (!this.searchParam ) this.tableList = cacheTableData
            if (this.searchParam == '全部' || this.searchParam == ''){
                this.tableList = cacheTableData
                return
            } 
            // console.log(cacheTableData);
            this.tableList = cacheTableData.filter(item => {
                return item[type] === this.searchParam
            })
        },
        arouseKeyBord (e) {
            const { target } = e
            const { childNodes } = target
            if (target.tagName === 'DIV') {
                if ((childNodes[0] && childNodes[0].nodeType === 3) || (childNodes[0] === undefined)) {
                    const path = require('path')
                    const exePath = process.env.NODE_ENV !== 'production' ? path.join(process.cwd(), 'bos_builder', 'ExecOSK.exe') : 'ExecOSK.exe'
                    const arouse = window.localStorage.getItem('arouse')
                    if (arouse === 'true' && !lockArouse) {
                        const exec = require('child_process').exec
                        lockArouse = true
                        exec(exePath, (err) => {
                            //成功执行的回调
                            if (!err) {
                                lockArouse = false
                            }
                        })
                    }
                }
            }
        },
        showToolkit () {
            this.active = !this.active
        },
        windowMin() {
            this.$electron.ipcRenderer.send("resource-window-minimize", {
                metaId: "mindMap",
            });
        },
        windowClose() {
            this.$electron.ipcRenderer.send("close-resource-window", {
                metaId: "mindMap",
            });
        },

    }
}
</script>

<style lang="scss">
#mindMap {
    width: 100%;
    height: 100vh;
    background-image: url(../../assets/img/echarts_bg.jpg);
    background-repeat: no-repeat;
    background-size: cover;
    position: relative;
    overflow: scroll;
    .mindmap-handle {
        padding: 15px 20px;
        max-width: 160px;
        max-height: 55px;
        background: #ffffff;
        box-shadow: 0px 1px 60px 0px rgba(184, 203, 215, 0.35);
        border-radius: 8px;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-left: 30px;
        // margin-bottom: 15px;
        cursor: pointer;
        .handle-img {
            width: 2.22vw;
            max-width: 30px;
            height: 2.22vw;
            max-height: 30px;
            margin-right: 8px;
            cursor: pointer;
        }
        .sub {
            color: rgba(#48afff, 0.8);
            display: inline-block;
            margin-right: 10px;
            font-size: 28px;
            i {
                font-weight: 900 !important;
            }
        }
        .handle-text {
            color: #606266;
            cursor: pointer;
        }
        
    }
    .mouse {
        width: 100%;
        height: 100%;
    }
    .tools {
        position: fixed;
        width: 100%;
        left: 0;
        bottom: 5vh;
        z-index: 999;
    }
    svg {
        background-color: transparent !important;
    }
}

</style>